import { ref, computed } from 'vue';

const RECENT_SEARCH_KEY = 'recent_search_keywords';
const MAX_RECENT_SEARCH = 3;

/**
 * 最近搜索功能的组合式函数
 */
export function useRecentSearch() {
  const recentSearchList = ref<string[]>([]);

  // 从本地存储加载最近搜索
  const loadRecentSearch = () => {
    try {
      const stored = localStorage.getItem(RECENT_SEARCH_KEY);
      if (stored) {
        recentSearchList.value = JSON.parse(stored);
      }
    } catch (error) {
      console.warn('加载最近搜索失败:', error);
      recentSearchList.value = [];
    }
  };

  // 保存到本地存储
  const saveRecentSearch = () => {
    try {
      localStorage.setItem(RECENT_SEARCH_KEY, JSON.stringify(recentSearchList.value));
    } catch (error) {
      console.warn('保存最近搜索失败:', error);
    }
  };

  // 添加搜索关键词
  const addRecentSearch = (keyword: string) => {
    if (!keyword || !keyword.trim()) return;
    
    const trimmedKeyword = keyword.trim();
    
    // 移除已存在的相同关键词
    const filteredList = recentSearchList.value.filter(item => item !== trimmedKeyword);
    
    // 添加到开头
    recentSearchList.value = [trimmedKeyword, ...filteredList].slice(0, MAX_RECENT_SEARCH);
    
    // 保存到本地存储
    saveRecentSearch();
  };

  // 删除指定搜索关键词
  const removeRecentSearch = (keyword: string) => {
    recentSearchList.value = recentSearchList.value.filter(item => item !== keyword);
    saveRecentSearch();
  };

  // 清空最近搜索
  const clearRecentSearch = () => {
    recentSearchList.value = [];
    saveRecentSearch();
  };

  // 是否有最近搜索记录
  const hasRecentSearch = computed(() => recentSearchList.value.length > 0);

  // 初始化时加载数据
  loadRecentSearch();

  return {
    recentSearchList,
    hasRecentSearch,
    addRecentSearch,
    removeRecentSearch,
    clearRecentSearch,
    loadRecentSearch
  };
}
